﻿using Autofac;
using Autofac.Extras.DynamicProxy;
using Blog.Framework.Internationalization;
using Blog.Repository.Base;
using Blog.Repository.Implementation;
using Blog.Repository.Interface;
using Blog.Service.Base;
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Blog.Framework.Extension
{
    public class AutofacModuleRegister : Autofac.Module
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(AutofacModuleRegister));
        protected override void Load(ContainerBuilder builder)
        {
            Assembly repositoryAssembly = typeof(BaseRepository<>).Assembly;
            Assembly serviceAssembly = typeof(BaseService<>).Assembly;

            if (repositoryAssembly == null)
            {
                _log.Fatal("依赖注入时无法获取到【仓储层】程序集！");
                throw new Exception(I18nMsg.tr("仓储层程序集为空！"));
            }

            if (serviceAssembly == null)
            {
                _log.Fatal("依赖注入时无法获取到【业务层】程序集");
                throw new Exception(I18nMsg.tr("业务层程序集为空！"));
            }

            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
            builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>)).InstancePerDependency();//注册仓储

            builder.RegisterAssemblyTypes(repositoryAssembly)
                //使用接口的方式进行注入
                .AsImplementedInterfaces()
                //开启属性注入
                .PropertiesAutowired()
                //默认模式，每次调用，都会重新实例化对象；每次请求都创建一个新的对象；
                .InstancePerDependency();


            builder.RegisterAssemblyTypes(serviceAssembly)
                //使用接口的方式进行注入
                .AsImplementedInterfaces()
                //开启属性注入
                .PropertiesAutowired()
                //默认模式，每次调用，都会重新实例化对象；每次请求都创建一个新的对象；
                .InstancePerDependency()
                //EnableClassInterceptors：适用于普通类和对象
                //EnableInterfaceInterceptors：适用于接口和实现类
                .EnableInterfaceInterceptors()
                ;


        }
    }
}
